package com.gpfei.score;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.SavedStateHandle;

public class MyViewModel extends AndroidViewModel {
    private int aBack, bBack,scoreA,scoreB;
    private SavedStateHandle handle;
    String keya = getApplication().getResources().getString(R.string.MY_KEYA);
    String keyb = getApplication().getResources().getString(R.string.MY_KEYB);

    public MyViewModel(@NonNull Application application, SavedStateHandle handle) {
        super(application);
        this.handle = handle;
        if (!handle.contains(keya) && !handle.contains(keyb)) {
            load();
        }
    }

    public MutableLiveData<Integer> getaTeamScore() {
        if (!handle.contains(MainActivity.NUMBER_A)) {
            handle.set(MainActivity.NUMBER_A, 0);
        }
        return handle.getLiveData(MainActivity.NUMBER_A);
    }

    public MutableLiveData<Integer> getbTeamScore() {
        if (!handle.contains(MainActivity.NUMBER_B)) {
            handle.set(MainActivity.NUMBER_B, 0);
        }
        return handle.getLiveData(MainActivity.NUMBER_B);
    }

    public void aTeamAdd(int a) {
        aBack = getaTeamScore().getValue();
        bBack = getbTeamScore().getValue();
        getaTeamScore().setValue(getaTeamScore().getValue() + a);
        scoreA = getaTeamScore().getValue();
        scoreB = getbTeamScore().getValue();
    }

    public void bTeamAdd(int b) {
        aBack = getaTeamScore().getValue();
        bBack = getbTeamScore().getValue();
        getbTeamScore().setValue(getbTeamScore().getValue() + b);
        scoreA = getaTeamScore().getValue();
        scoreB = getbTeamScore().getValue();
    }

    public void reset() {
        aBack = getaTeamScore().getValue();
        bBack = getbTeamScore().getValue();
        getaTeamScore().setValue(0);
        getbTeamScore().setValue(0);
    }

    public void undo() {
        getaTeamScore().setValue(aBack);
        getbTeamScore().setValue(bBack);
    }
    public void save() {
        String name = getApplication().getResources().getString(R.string.MY_DATA);
        SharedPreferences sp = getApplication().getSharedPreferences(name, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(keya, scoreA);
        editor.putInt(keyb, scoreB);
        editor.apply();
    }
    public void load() {
        String name = getApplication().getResources().getString(R.string.MY_DATA);
        SharedPreferences sp = getApplication().getSharedPreferences(name, Context.MODE_PRIVATE);
        getaTeamScore().setValue(sp.getInt(keya, getApplication().getResources().getInteger(R.integer.defValue)));
        getbTeamScore().setValue(sp.getInt(keyb, getApplication().getResources().getInteger(R.integer.defValue)));
    }
}
